package com.yang.game;

import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.squareup.okhttp.Request;
import com.yang.game.model.User;
import com.yang.game.utils.OkHttpClientManager;

public class MainActivity extends AppCompatActivity {

    private Button loginBtn, toRegisterBtn;
    private TextView account;
    private TextView password;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        loginBtn = findViewById(R.id.loginBtn);
        toRegisterBtn = findViewById(R.id.toRegisterBtn);
        account = findViewById(R.id.accountText);
        password = findViewById(R.id.passwordText);

        loginBtn.setOnClickListener(v -> {
            Intent intent = new Intent(MainActivity.this, InfoActivity.class);
            String strAccount = account.getText().toString();
            String strPassword = password.getText().toString();
            if (strAccount.isEmpty()) {
                Toast.makeText(MainActivity.this, "账号为空", Toast.LENGTH_LONG).show();
            } else if (strPassword.isEmpty()) {
                Toast.makeText(MainActivity.this, "密码为空", Toast.LENGTH_LONG).show();
            } else {
                OkHttpClientManager.Param param1 = new OkHttpClientManager.Param("account", strAccount);
                OkHttpClientManager.Param param2 = new OkHttpClientManager.Param("password", strPassword);
                OkHttpClientManager.postAsyn("http://10.99.212.127:9090/api/user/login", new OkHttpClientManager.ResultCallback<User>() {
                    @Override
                    public void onError(Request request, Exception e) {

                    }
                    @Override
                    public void onResponse(User queryUser) {
                        if (queryUser == null) {
                            password.setText("");
                            Toast.makeText(MainActivity.this, "用户不存在或密码错误", Toast.LENGTH_LONG).show();
                            return;
                        }
                        intent.putExtra("id", queryUser.getId());
                        intent.putExtra("account", strAccount);
                        intent.putExtra("password", strPassword);
                        Toast.makeText(MainActivity.this, "登录成功", Toast.LENGTH_LONG).show();
                        startActivity(intent);
                    }
                }, param1, param2);
            }
        });

        toRegisterBtn.setOnClickListener(v -> {
            Intent intent = new Intent(MainActivity.this, RegisterActivity.class);
            startActivity(intent);
        });
    }


}
